package com.example.controller;

import com.example.model.MessageInfo;
import com.example.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @RequestMapping("/getList")
    public List<MessageInfo> getList(){
        log.info("查询所有留言");
        return messageService.getList();
    }

    @RequestMapping(value = "/publish", produces = "application/json")
    public String publish(@RequestBody MessageInfo messageInfo) {

        log.info("发布留言, messageInfo:{}", messageInfo);
        //参数校验
        if (!StringUtils.hasLength(messageInfo.getMessage())
                || !StringUtils.hasLength(messageInfo.getFrom())
                || !StringUtils.hasLength(messageInfo.getTo())){
            return "{\"ok\":0}";
        }
        try {
            Integer result = messageService.insertMessage(messageInfo);
            return result==1 ? "{\"ok\":1}" : "{\"ok\":0}";
        }catch (Exception e){
            log.error("发布留言失败, e:", e);
            return "{\"ok\":0}";
        }

    }
}
